const Router = require('koa-router')
const { TokenValidator } = require('../../validators/validator')
const { LoginType } = require('../../lib/enum')
const { User } = require('../../models/user')
const { generateToken } = require('../../../core/util')

const router = new Router({
    prefix: '/v1/token'  //指定所有注册在路由上的中间件前缀
})

router.post('/', async (ctx, next) => {
    const v = await new TokenValidator().validate(ctx)
    //type处理
    let token;
    switch (v.get('body.type')) {
        case LoginType.USER_EMAIL:
            token = await emailLogin(v.get('body.account'), v.get('body.secret'))
            break;
        case LoginType.USER_MINI_PROGRAM:

            break;

        default:
            throw new global.errs.ParameterException('没有相应的处理函数')//没有匹配项
            break;
    }
    ctx.body = {
        token //将生成的token返回接口
    }
})
async function emailLogin(account, secret) {
    //根据账号查询数据库密码,进行比对
    const user = await User.verifyEmailPassword(account, secret)
    return token = generateToken(user.id, 2)//生成token并返回
}

module.exports = router